import { useUserStoreHook } from '@/store/modules/user'
import { useTopologyEditorStoreOutside } from '@/store/modules/topology-editor'
import { SOCKET_HTTP_URL } from '@/constant';
import { configurationPageStore } from '@/store/modules/configurationPage';
import { storageLocal } from '@pureadmin/utils';
import { getToken, userKey } from '@/utils/auth';

type commonResult<T> = {
    code: number;
    msg: string;
    result: T;
};

const useUserStore = ref(useUserStoreHook())
const topologyEditorStoreOutside = ref(useTopologyEditorStoreOutside())

let token = getToken().accessToken.split(' ')[1];
const connectWebsocket = (projectId, topoId) => {
    // yc.tst.fourwell.net
    window.meta2d.connectWebsocket(`wss://${SOCKET_HTTP_URL}/system/ws/${storageLocal().getItem(userKey).userInfo?.id}_${new Date().getTime()}/topo_${projectId}_${topoId}/${token}`)
    // window.meta2d.connectWebsocket(`ws://192.168.1.62:8088/system/ws/${storageLocal().getItem(userKey).userInfo?.id}_${new Date().getTime()}/topo_${projectId}_${topoId}/${token}`)
}
const connectHttp = (projectId) => {
    window.meta2d.store.data.httpHeaders = {
        "Authorization": getToken().accessToken
    };
    window.meta2d.store.data.http = `https://${SOCKET_HTTP_URL}/topo/topo/v2/project-real-data/${projectId}`
    // window.meta2d.store.data.http = `https://${SOCKET_HTTP_URL}/topo/topo/v2/project-real-data/${projectId}`
    // window.meta2d.store.data.http = `http://192.168.1.62:8088/topo/topo/v2/project-real-data/${projectId}`
    window.meta2d.store.data.httpTimeInterval = 5000 // 轮询间隔时间, 默认 1000
    window.meta2d.connectHttp()
}
const closeHttpAndWebsocket = () => {
    window.meta2d.closeHttp()
    window.meta2d.closeWebsocket()
}
const reHttpAndWebsocket = () => {
    let store = configurationPageStore()
    closeHttpAndWebsocket()
    if (store.source == 'manage') {
    } else {
        connectHttp(store.projectId)
        connectWebsocket(store.projectId, store.topoId)
        setCustomParseFun()
    }
}
const setCustomParseFun = () => {
    const customParseFun = (e) => {
        const res = JSON.parse(e)
        const data = Array.isArray(res) ? res : [res]
        data.forEach((item) => {
            if (item.tag) {
                window.meta2d.find(item.tag).forEach((pen) => {
                    if (pen.echarts.name == "lineChart" || pen.name == "barChart") {
                        pen.form.find(dadaForm => dadaForm.key == "dataY").dataIds?.forEach((ids, index) => {
                            ids.name = item['echarts.option.xAxis.data'][index]
                            window.meta2d.initBindDatas();
                        })
                    }
                })
            }
        })
        return true;
    }
    window.meta2d.store.data.socketCbJs = `
      const customFun = ${customParseFun}
      return customFun(e)
      `
    window.meta2d.listenSocket()
}

const getRequest = (func: (params?: object) => Promise<commonResult<any>>, params?: object) => {
    return topologyEditorStoreOutside.value.getRequestCache(func, params)
}

export { reHttpAndWebsocket, closeHttpAndWebsocket, getRequest }